using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using NetProtocol.Enum;
using NetProtocol.POD;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class UIBattleSettlement : UIBaseWindow
    {
        /// <summary>
        /// 静态配置
        /// </summary>
        private static UICreateConfig _createConfig = new()
        {
            prefabName = nameof(UIBattleSettlement),
            layer = EUILayer.Normal,
        };

        /// <summary>
        /// 创建UI的配置
        /// </summary>
        public override IUICreateConfig createConfig => _createConfig;

        #region Template Generate,don't modify

        protected partial class UIB_UIBattleSettlement
        {
            #region ObjectBinding Generate

            public IQIGame.Onigao.Framework.ExButton btnConfirm { protected set; get; }
            public GameObject panelVictory { protected set; get; }
            public GameObject panelFail { protected set; get; }
            public GameObject settlementHero { protected set; get; }
            public GameObject common_Item { protected set; get; }
            public GameObject rewardList { protected set; get; }
            public GameObject heroList { protected set; get; }
            public GameObject monsterWeak { protected set; get; }

            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btnConfirm", out var __tbv0);
                this.btnConfirm = __tbv0;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("panelVictory", out var __tbv1);
                this.panelVictory = __tbv1;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("panelFail", out var __tbv2);
                this.panelFail = __tbv2;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("settlementHero", out var __tbv3);
                this.settlementHero = __tbv3;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("common_Item", out var __tbv4);
                this.common_Item = __tbv4;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("rewardList", out var __tbv5);
                this.rewardList = __tbv5;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("heroList", out var __tbv6);
                this.heroList = __tbv6;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("monsterWeak", out var __tbv7);
                this.monsterWeak = __tbv7;
            }

            #endregion ObjectBinding Generate
        }

        #endregion Template Generate,don't modify

        protected UIB_UIBattleSettlement ui { get; set; }

        private UIItemPool<UIN_SettlementHero> _heroPool;
        private UIItemPool<UIN_WeaknessItem> _weaknessPool;
        private ListScrollAdapter<UIN_OneItem> questRewards = null;

        private List<(int, int)> rewards;

        protected override void BeforeInit()
        {
            ui = new UIB_UIBattleSettlement();
            ui.InitBinding(this.csObjBind);
        }

        protected override void OnInit()
        {
            this._heroPool = this.InitPool<UIN_SettlementHero>(this.ui.settlementHero);
            this.ui.settlementHero.SetActive(false);

            this._weaknessPool = this.InitPool<UIN_WeaknessItem>(this.ui.monsterWeak);
            this.ui.monsterWeak.SetActive(false);

            this.questRewards = this.InitListScroll<UIN_OneItem>(this.ui.common_Item, this.OnRewardChanged);

            this.ui.btnConfirm.onClick.AddListener(this.OnClickConfirm);
        }

        protected override void OnShow(UIBaseData data)
        {
            if (data is not UD_BattleSettlement d)
            {
                return;
            }
            if (d.settlementData is BattleSettlementData rData)
            {
                var bSuccess = rData.resultType == BattleResultType.Success;
                this.ui.panelVictory.SetActive(bSuccess);
                this.ui.panelFail.SetActive(!bSuccess);

                if (bSuccess)
                {
                    var nMaxDamage = 0;
                    var nMaxHurt = 0;
                    var nMaxCure = 0;
                    for (int i = 0; i < rData.statisticsPods.Count; i++)
                    {
                        var rStat = rData.statisticsPods[i];
                        nMaxDamage += rStat.damage;
                        nMaxHurt += rStat.hurt;
                        nMaxCure += rStat.cure;
                    }

                    for (int i = 0; i < rData.statisticsPods.Count; i++)
                    {
                        var rHead = this._heroPool.GetOne();
                        rHead.Initialize(rData.statisticsPods[i], nMaxDamage, nMaxHurt, nMaxCure);
                    }
                    this.rewards = rData.rewards;
                    int cnt = this.rewards?.Count ?? 0;
                    this.questRewards.RefillCells(cnt);
                    this.ui.rewardList.SetActive(cnt > 0);
                    // int cntRwd = cfgQuest.Reward.Count / APIUIConst.RewardDefaultSpacing;
                }
                else
                {
                    // 根据monsterTeam获取弱点列表
                    if (rData.allMonsterTeam.Count > 0)
                    {
                        var rWeakNum = new int[(int)EWeaknessType.Max];
                        var rList = new List<int>();
                        var nMonsterTeam = rData.allMonsterTeam[0];
                        var rMonsterTeamConfig = TableCenter.monsterTeam.Get(nMonsterTeam);
                        for (int j = 0; j < rMonsterTeamConfig.MonsterId.Count; j++)
                        {
                            var nMonsterID = rMonsterTeamConfig.MonsterId[j];
                            var rConfig = TableCenter.monster.Get(nMonsterID);
                            for (int k = 0; k < rConfig.WeakType.Count; k++)
                            {
                                rList.Add(rConfig.WeakType[k]);
                            }
                        }
                        // 分组并按数量排序
                        var rSortedGroups = rList.GroupBy(x => x)
                            .OrderByDescending(g => g.Count())
                            .Select(g => g.Key).ToList();
                        for (int i = 0; i < rSortedGroups.Count; i++)
                        {
                            var rType = (EWeaknessType)rSortedGroups[i];
                            var rWeak = this._weaknessPool.GetOne();
                            rWeak.ShowByData(rType);
                        }
                    }
                }
            }
        }

        protected override void OnShow()
        {

        }

        protected override void OnHide()
        {

        }

        protected override void OnDispose()
        {
        }

        void OnRewardChanged(UIN_OneItem item, int index)
        {
            var rItem = this.rewards[index];
            item.Show(rItem.Item1, rItem.Item2);
        }

        void OnClickConfirm()
        {
            CBattleLogicModule.NetCore.CS_RequestLeave();
            this.Close();
        }
    }

    public class BattleSettlementData
    {
        public BattleResultType resultType;

        // public List<BattleUnitStatistics> statistics = new List<BattleUnitStatistics>();
        public List<int> allMonsterTeam = new List<int>(); // 所有怪物队伍的ID
        public List<BattleStatisticsUnitPOD> statisticsPods = new List<BattleStatisticsUnitPOD>();

        public List<(int, int)> rewards = new List<(int, int)>();

        public static BattleSettlementData Parse(BattleSettlementPOD settlementPOD)
        {
            BattleSettlementData data = new BattleSettlementData();
            data.resultType = settlementPOD.resultType;
            data.statisticsPods = settlementPOD.statisticsPOD.units;
            return data;
        }
    }
}
